package com.gyms.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.classic.okhttp.RequestBeans.HVAddVenueOrderListRequestBean;
import com.classic.okhttp.RequestBeans.HVAddVenueOrderRequestBean;
import com.classic.okhttp.beans.HVAddOrderBean;
import com.classic.okhttp.beans.HVVenueFieldBean;
import com.classic.okhttp.beans.HVVenueItemBean;
import com.classic.okhttp.beans.HVVenueItemInfoBean;
import com.classic.okhttp.beans.HVVenueWeekTimesBean;
import com.classic.okhttp.beans.HVVenueWeekTimesInfoBean;
import com.classic.okhttp.comparator.SortByStartTime;
import com.classic.okhttp.enums.Enum;
import com.classic.okhttp.services.IOrderService;
import com.classic.okhttp.services.IVenueService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.gyms.R;
import com.gyms.adapter.SeatOrderAdapter;
import com.gyms.adapter.SeatTabAdapter;
import com.gyms.base.BaseActivity;
import com.gyms.constant.Constants;
import com.gyms.manager.CommonDialogUtils;
import com.gyms.manager.DataCenter;
import com.gyms.manager.SeatFieldManger;
import com.gyms.manager.SeatOrderManger;
import com.gyms.manager.StatisticsManager;
import com.gyms.manager.TitleManager;
import com.gyms.view.bottomview.ShareDialog;
import com.orhanobut.logger.Logger;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import constant.EventConstant;
import constant.PicSplit;
import utils.DateUtil;
import utils.DecimalUtils;
import utils.ScreenUtils;
import utils.SizeUtils;
import utils.StringUtils;
import weight.ComDialog;
import weight.HorizontalListView;
import weight.MyHroScrollView;
import weight.UiEvent;

/**
 * 选座
 * ltx
 */

public class SeatChoseActivity extends BaseActivity implements MyHroScrollView.ScrollViewListener, View.OnClickListener {
    @BindView(R.id.hv_1)
    HorizontalScrollView mHv1;
    @BindView(R.id.mv_seat)
    MyHroScrollView mMvSeat;
    @BindView(R.id.ll_time)
    LinearLayout mLlTime;//时间栏
    @BindView(R.id.ll_gym_number)
    LinearLayout mLlGymNumber;//场次
    @BindView(R.id.ll_seat_item)
    LinearLayout mLlSeatItem;//放seatItem的LinearLayout
    @BindView(R.id.rv_seat_selected)
    RecyclerView mRvSeatSelected;//选择的座位的订单
    @BindView(R.id.ll_seat_order_layout)
    LinearLayout mLlSeatOrderLayout;//有订座出现无订座隐藏
    @BindView(R.id.tv_seat_price)
    TextView mTvSeatPrice;
    //横向tab
    @BindView(R.id.hv_seat_tab)
    HorizontalListView mHvSeatTab;
    @BindView(R.id.sv_seat_all)
    ScrollView mSvVertical;//纵向的scrollView
   /* @BindView(R.id.ll_seat_order_bottom)
    LinearLayout mLlSeatOrderBottom;//底部显示的价格*/

    private List<HVVenueItemBean> mOrderHVVenueItemBean = new ArrayList<>();//选择座位存放的list
    private List<String> mDateAndWeekList = new ArrayList<>();
    private HashMap<Integer, List<HVVenueItemBean>> mpHVVenueItemBean;//所有场馆的场地的存放的map
    private HashMap<String,View> mMpSelectBeans=new HashMap<>();//以场次的ItemId为key 存放选中的View
    private SeatOrderManger mSeatOrderManger;
    private final static int ADD = 1;//选择
    private final static int CANCEL = 2;//取消
    private  int mMaxCount = 3;//最多只能选三个


    //周次场次信息
    private List<HVVenueWeekTimesBean> mHVVenueWeekTimesBeanList = new ArrayList<>();
    private HVVenueItemInfoBean mHVVenueItemInfoBean;//订座的信息的bean
    //场馆场次信息集合
    private ArrayList<HVVenueItemBean> venueItemList;
    //场馆场地信息集合
    private ArrayList<HVVenueFieldBean> venueFieldList;
    private SeatOrderAdapter mSeatOrderAdapter;

    private double mAllPrice;//总共价格

    private SeatTabAdapter mSeatTabAdapter;//tabAdapter

    private String venueId, projectId;
    private int mWeekPos;//选择的日期的位置
    //按时间来计算
    private int startTime, endTime;//开始时间 结束时间
    private final static int SINGLEHEIGH = 30;
    private final static int SINGLEWIDTH = 50;

    private final static int TEN_DP = 10;//10dp
    private final static int ELEVEN_DP = 11;//11dp
    private String mProjectName;
    private int mCurPos=-1;//当前的所在的tabpos  如果当前的就不刷新

    private List<String> mFieldNameList=new ArrayList<>();//场地名的数组

    //选择的时间 用于初始化
    private int mCurTime;
    //购买须知相关
    private ImageView mIvBuyInfo;//特殊说明

    private String mVenueItemSpecific;
    //分享相关
    private ShareDialog mShareDialog;//分享框
    private ImageView mIvShare;//分享
    private String mShortAdress;//短地址
    private String mGymName;//场馆名称


    @Override
    protected void setTitleTheme() {
        mTheme = TitleManager.TitleTheme.White;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_seat_chose;
    }

    @Override
    protected void initView() {
        createLoadingView("加载中", true);
        Bundle mBundle = getIntent().getExtras();
        if (null != mBundle) {
            venueId = mBundle.getString(Constants.FLAG_INTENT_VENUEID, "");//场馆iD
            projectId = mBundle.getString(Constants.FLAG_INTENT_PROJECT_ID, "");//运动项目Id
            mWeekPos = mBundle.getInt(Constants.FLAG_INTENT_SELECT_POS, 0);//初始化显示星期几
            mCurTime=mBundle.getInt(Constants.FLAG_INTENT_CHOSE_TIME,0);
            mCurPos=mWeekPos;
           /* mProjectName = mBundle.getString(Constants.FLAG_INTENT_PROJECTNAME_SEAT, "");//获取预定项目名称*/
        }
        setBack();
        doInitView();

        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRvSeatSelected.setLayoutManager(linearLayoutManager);
        //设置适配器
        mSeatOrderAdapter = new SeatOrderAdapter(mContext);
        mRvSeatSelected.setAdapter(mSeatOrderAdapter);

        mMvSeat.setScrollViewListener(this);//设置滑动联动
        mSeatOrderManger = SeatOrderManger.getInstance();
        initSeatTab();
        //设置高度
        ViewGroup.LayoutParams mLlSvVertical=mSvVertical.getLayoutParams();
        mLlSvVertical.height= ScreenUtils.getScreenHeight(this)/3;
        mSvVertical.setLayoutParams(mLlSvVertical);

    }

    private void doInitView() {
        mIvBuyInfo=mTitleManager.setRightView(R.mipmap.icon_shuoming);
        mIvShare=mTitleManager.setRightViewR(R.mipmap.icon_fenxiang);
        mIvBuyInfo.setVisibility(View.GONE);
    }

    @Override
    protected void setListener() {
        /**
         * 设置横向的不可滑动
         */

        mHv1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                return true;
            }
        });
        EventBus.getDefault().register(this);
        //tablan的点击
        mHvSeatTab.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //场馆预定下单点击日期
                StatisticsManager.onEvent(mContext, StatisticsManager.SiteDetail_Date);

                HVVenueWeekTimesBean mHVVenueWeekTimesBean = mHVVenueWeekTimesBeanList.get(position);
                if (mHVVenueWeekTimesBean.getIsBook()&&mCurPos!=position) {//
                    mSeatTabAdapter.setSelection(position);
                    mSeatTabAdapter.notifyDataSetChanged();
                    //更新数据源
                    int time = mHVVenueWeekTimesBeanList.get(position).getVenueTime();
                    getVenueItemList(time);
                }
                mCurPos=position;
            }
        });
        mIvBuyInfo.setOnClickListener(this);
        mIvShare.setOnClickListener(this);

    }

    @Override
    protected void processLogic() {
        getVenueWeekTimesList();
    }

    /**
     * 获取场次信息
     *
     * @param time 时间戳
     */

    private void getVenueItemList(int time) {
        loadingView.show();
        IVenueService.getVenueItemList(this, venueId, projectId, time, false, new ObjectCallback<HVVenueItemInfoBean>() {
            @Override
            public void onSuccess(HVVenueItemInfoBean response, String message) {
                dialogDis();
                doClearAllViews();
                if (response != null) {
                    mHVVenueItemInfoBean = response;
                    SeatFieldManger.getInstance().setVenueFieldList(response.getVenueFieldList());
                    doShowVebueItem();
                }
            }

            @Override
            public void onErrorT(int code, HVVenueItemInfoBean response, String errorMessage) {
                dialogDis();
                doClearAllViews();
                Logger.e(errorMessage);
                ToastUtil.showToast(mContext, errorMessage);
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
                doClearAllViews();
                Logger.e("statusCode" + statusCode);
                ToastUtil.showToast(mContext, statusCode + "");
            }
        });

    }

    /**
     * 展示场馆
     */

    private void doShowVebueItem() {
        doShowTimeItem();
        doShowVeNum();
        //改变已选的view的状态
        doUpdateStaue();
        doShowVe();
    }

    /**
     *  加载之前remove 所加的item
     */

    private void doClearAllViews() {
        mLlTime.removeAllViews();
        mLlGymNumber.removeAllViews();
        mLlSeatItem.removeAllViews();
    }

    /**
     * 更新状态
     */

    private void doUpdateStaue() {
        if (StringUtils.isNull(mOrderHVVenueItemBean) || StringUtils.isNull(mHVVenueItemInfoBean.getVenueItemList())) {//无选择状态不需要更新
            return;
        }
        for (HVVenueItemBean mHVVenueItemBean : mOrderHVVenueItemBean) {
            String mVenueItemId = mHVVenueItemBean.getVenueItemId();
            for (HVVenueItemBean mHVVenueItemBeanChild : mHVVenueItemInfoBean.getVenueItemList()) {
                String mVenueItemChildId = mHVVenueItemBeanChild.getVenueItemId();
                if (mVenueItemId.equals(mVenueItemChildId)) {
                    mHVVenueItemBeanChild.setIsSelected(mHVVenueItemBean.getIsSelected());
                    break;
                }
            }

        }


    }

    /**
     * 展示具体的场地
     */

    private void doShowVe() {
        venueItemList = mHVVenueItemInfoBean.getVenueItemList();

        mpHVVenueItemBean = new HashMap<>();
        for (int i = 0; i < venueFieldList.size(); i++) {//遍历场地的id将相同场地的场次信息放在一块
            HVVenueFieldBean mHVVenueFieldBean = venueFieldList.get(i);//场地号的bean
            String fieldId = mHVVenueFieldBean.getVenueFieldId();//场地号的iD
            List<HVVenueItemBean> mHVVenueItemBeanList = new ArrayList<>();//一个纵向的列表,按场地排列,如fieldId相同add
            for (int j = 0; j < venueItemList.size(); j++) {//场地的详情Item
                HVVenueItemBean mHVVenueItemBean = venueItemList.get(j);//获取单个itembean
                if (fieldId.equals(mHVVenueItemBean.getVenueFieldId())) {//跟filediD进行比较
                    mHVVenueItemBeanList.add(mHVVenueItemBean);
                }
            }

            Collections.sort(mHVVenueItemBeanList, new SortByStartTime());//排序
            mpHVVenueItemBean.put(i, mHVVenueItemBeanList);//按场地号为key，生成的itemlist的hashmap

        }
        doAddVeItem(mpHVVenueItemBean);
    }

    /**
     * 将场地的ItemAdd进来
     *
     * @param mpHVVenueItemBean 按场地号为key，生成的itemlist的hashmap
     */

    private void doAddVeItem(HashMap<Integer, List<HVVenueItemBean>> mpHVVenueItemBean) {
        for (int p = 0; p < mpHVVenueItemBean.size(); p++) {//动态生成ItemLinearLayout
            List<HVVenueItemBean> mHVVenueItemBeans = mpHVVenueItemBean.get(p);
            LinearLayout mLlItem = new LinearLayout(mContext);
            mLlItem.setLayoutParams(new ViewGroup.LayoutParams(SizeUtils.dp2px(mContext, 50), ViewGroup.LayoutParams.WRAP_CONTENT));
            mLlItem.setOrientation(LinearLayout.VERTICAL);
            for (int i = 0; i < mHVVenueItemBeans.size(); i++) {//动态生成Item
                HVVenueItemBean mHVVenueItemBean = mHVVenueItemBeans.get(i);
//                if(i>=mHVVenueItemBeans.size()-3){
//                    mHVVenueItemBean.setItemStartTime(mHVVenueItemBean.getItemStartTime()+6*60*60);
//                    mHVVenueItemBean.setItemEndTime(mHVVenueItemBean.getItemEndTime()+6*60*60);
//                }
                TextView mTextView = new TextView(mContext);
                float mTimeDis = getTimeDis(mHVVenueItemBean);
                mTextView.setClickable(true);
                mTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP,TEN_DP);
                LinearLayout.LayoutParams mTvParams = new LinearLayout.LayoutParams(
                SizeUtils.dp2px(mContext, SINGLEWIDTH), SizeUtils.dp2px(mContext, SINGLEHEIGH * mTimeDis));
                mTextView.setGravity(Gravity.CENTER);//居中
                setViewStyle(mHVVenueItemBean, mTextView);
                if (Constants.SEAT_SOLD != mHVVenueItemBean.getItemState().value) {//不是已售就设置监听，并且设置价格
                    mTextView.setTag(mHVVenueItemBean);
                    List<Object> seatInForList = new ArrayList<>();//存放bean的位置 先存场号的再存场地的
//                    mTextView.setText(getResources().getString(R.string.tet_money) + doubleToIntOrD(mHVVenueItemBean.getPrice()));//设置价钱
                    mTextView.setText( DecimalUtils.setPriceStyle(mContext,mHVVenueItemBean.getPrice(),R.dimen.price_text_size_10,R.dimen.price_text_size_8,true));//设置价钱
                    seatInForList.add(p);//场地号的position
                    seatInForList.add(i);//时间的postion
                    seatInForList.add(mpHVVenueItemBean);//将整个数据集add
                    mTextView.setTag(seatInForList);
                    mTextView.setOnClickListener(new ClickItem());
                }
                if (i == 0) {//第一个来计算与开始时间比较 设置marginTop
                    int mItemStartTimeS=mHVVenueItemBean.getItemStartTime();
                    int s = DateUtil.intToHourGetInt(mItemStartTimeS);//第一个Item起始小时
                    /*if(!DateUtil.isToday(mItemStartTimeS)){//如果不是当天就加上24小时
                        s=s+24;
                    }*/
                    float min=DateUtil.intToMinGetInt(mHVVenueItemBean.getItemStartTime())/(float)60;//第一个Item起始分钟 支持半小时
                    float mItemSDis = (s - startTime)+min;//item的开始小时与StartTime的减
                    mTvParams.setMargins(0, SizeUtils.dp2px(mContext, SINGLEHEIGH * mItemSDis), 0, 0);
                    mTextView.setLayoutParams(mTvParams);
                } else {//与上一个比较计算上一个的时间差距设置margin
                    HVVenueItemBean mPremHVVenueItemBean = mHVVenueItemBeans.get(i - 1);
                    float mItemTimeDIs = getItemSToStTime(mHVVenueItemBean, mPremHVVenueItemBean);
                    mTvParams.setMargins(0, SizeUtils.dp2px(mContext, SINGLEHEIGH * mItemTimeDIs), 0, 0);
                    mTextView.setLayoutParams(mTvParams);
                }
                mLlItem.addView(mTextView);
                /**
                 *上次选中的重新add
                 */
                for(HVVenueItemBean mHVVenueItemBeanOrdered:mOrderHVVenueItemBean){
                    //已选择的订单的Bean的id
                    String mVenueItemId=mHVVenueItemBeanOrdered.getVenueItemId();
                    if(mVenueItemId.equals(mHVVenueItemBean.getVenueItemId())){
                        //add之前就先移除
                        mMpSelectBeans.remove(mVenueItemId);
                        mMpSelectBeans.put(mVenueItemId,mTextView);
                    }
                }
            }

            mLlSeatItem.addView(mLlItem);

        }
    }

    /**
     * 设置View的样式
     *
     * @param mHVVenueItemBean itemBean
     * @param mTextView        设置的vIew
     */

    private void setViewStyle(HVVenueItemBean mHVVenueItemBean, TextView mTextView) {
        if (mHVVenueItemBean.getItemState().value == Constants.SEAT_SOLD) {//已售出的状态
            mTextView.setBackgroundResource(R.drawable.sp_seat_sold);
        } else if (mHVVenueItemBean.getIsSelected() == Constants.SEAT_SELECTED) {//已选择
            mTextView.setBackgroundResource(R.drawable.sp_seat_selcted);
            mTextView.setTextColor(getResources().getColor(R.color.white));//设置为白色
        } else if (mHVVenueItemBean.getIsSelected() == Constants.SEAT_CAN_SELECT) {//可选择
            mTextView.setBackgroundResource(R.drawable.sp_seat_nom);
            mTextView.setTextColor(getResources().getColor(R.color.c_333333));//设置为黑色
        }
    }


    @OnClick(R.id.tv_order)//确认 下订单 去订单详情页面
    public void onClick() {
        if(!DataCenter.getInstance().checkIsLogin()){//检查是否登录
            startActivity(CodeLoginActivity.class,false);
            return;
        }
        addVenueOrder();
    }

    /**
     * 生成场次信息
     */

    private void addVenueOrder() {
        //组装请求bean
        if (null == mOrderHVVenueItemBean || mOrderHVVenueItemBean.size() == 0) {
            ToastUtil.showToast(mContext, "请选择你要预定的场次");
            return;
        }
        ArrayList<HVAddVenueOrderRequestBean> order = new ArrayList<>();
        for (HVVenueItemBean mHVVenueItemBean : mOrderHVVenueItemBean) {
            HVAddVenueOrderRequestBean bean = new HVAddVenueOrderRequestBean();
            bean.setItemEndTime(mHVVenueItemBean.getItemEndTime());
            bean.setItemStartTime(mHVVenueItemBean.getItemStartTime());
            bean.setPrice(mHVVenueItemBean.getPrice());
            bean.setItemId(mHVVenueItemBean.getVenueItemId());
            order.add(bean);
        }
        //组装请求bean
        HVAddVenueOrderListRequestBean mHVAddVenueOrderListRequestBean=new HVAddVenueOrderListRequestBean();
        mHVAddVenueOrderListRequestBean.setOrder(order);
        mHVAddVenueOrderListRequestBean.setTotalPrice(mAllPrice);
        loadingView.show();
        IOrderService.addOrderV2(this, Enum.EnumCollect.Venue , mHVAddVenueOrderListRequestBean,null, false, new ObjectCallback<HVAddOrderBean>() {
            @Override
            public void onSuccess(HVAddOrderBean response, String message) {
                dialogDis();
                if (!StringUtils.isNull(response)) {
                    String mOrderId = response.getOrderId();
                    Bundle mBundle = new Bundle();
                    mBundle.putString(Constants.FLAG_INTENT_GYM_ORDER_ID, mOrderId);//订单Id
                    mBundle.putString(Constants.FLAG_INTENT_IS_CONFIRM, Constants.FLAG_INTENT_IS_CONFIRM);//标识是订单确认页面
                    mBundle.putString(Constants.FALG_INTENT_FROM_GYM, Constants.FALG_INTENT_FROM_GYM);//标识是订单确认页面
                    mBundle.putInt(Constants.FLAG_INTENT_UNPAY_TYPE,Constants.GYM_ORDER_TYPE);//场馆的订单
                    startActivity(OrderDetailActivity.class, mBundle,false);
                }
            }

            @Override
            public void onErrorT(int code, HVAddOrderBean response, String errorMessage) {
                if(!StringUtils.isNull(response)){
                    String mNotPayOrderId=response.getNotPayOrderId();//未支付的订单号
                    int mOrderType=response.getNotPayOrderType().value;//未支付的订单类型
                    if(!StringUtils.isNull(mNotPayOrderId)){//先支付
                        doMustPay(mNotPayOrderId,mOrderType);
                    }else if(!StringUtils.isNull(response.failedItemIdList)){//有订单被抢
                        doShowCancelDialog(response.failedItemIdList);
                    }
                }else{
                    ToastUtil.showToast(mContext, errorMessage);
                }
                dialogDis();
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                ToastUtil.showToast(mContext,"statusCode="+statusCode);
                dialogDis();
            }
        });
    }

    /**
     * 弹框提示 先支付才能继续支付
     * @param mNotPayOrderId 未支付的订单号
     * @param mOrderType 未支付的订单类型
     */

    private void doMustPay(final String mNotPayOrderId, final int mOrderType) {
        final ComDialog dialog = CommonDialogUtils.dialog(SeatChoseActivity.this,getSupportFragmentManager(),getString(R.string.str_order_remind), getString(R.string.order_must_pay), getString(R.string.str_pay_sub), getString(R.string.str_cancel));
        dialog.setSubmit(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Bundle mBundle=new Bundle();
                mBundle.putString(Constants.FLAG_INTENT_GYM_ORDER_ID,mNotPayOrderId);
                if(mOrderType==Constants.PRODUCT_ORDER_TYPE){//产品订单
                    mBundle.putInt(Constants.FALG_INTENT_PRODUCT_TAG, Constants.PRODUCT_ORDER_TYPE);//标识是产品订单
                }
                mBundle.putString(Constants.FLAG_INTENT_IS_CONFIRM, Constants.FLAG_INTENT_IS_CONFIRM);//标识是订单确认页面
                mBundle.putString(Constants.FALG_INTENT_FROM_GYM, Constants.FALG_INTENT_FROM_GYM);//标识是订单确认页面
                startActivity(OrderDetailActivity.class,mBundle,false);

            }
        });
        dialog.setCancel(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_img_right://特殊说明点击
//                ToastUtil.showLongToast(mContext,"购买须知");
                Bundle mBundle= new Bundle();
                mBundle.putString(Constants.WEBVIEW_STR_HTML,mVenueItemSpecific);
                mBundle.putString(Constants.WEBVIEW_TITLE,getString(R.string.buy_must_know));
                startActivity(WebViewActivity.class,mBundle,false);
                break;
            case R.id.iv_img_right_right:
                if(null==mShareDialog){
                    mShareDialog=new ShareDialog(this,R.style.BottomToTopAnim);
                    mShareDialog.setTitle(PicSplit.makeShareTitle(mGymName,mProjectName));
                    String mShareGymUrl= PicSplit.makeShareUrl(PicSplit.S_VENUE_ID,venueId,PicSplit.S_PROJECT_ID,projectId);
                    Log.e("shareUrl",mShareGymUrl);
                    mShareDialog.setTagUrl(mShareGymUrl);
                    mShareDialog.setShareContent(PicSplit.makeSHareContent(mShortAdress));
                }
                mShareDialog.show();
                break;
        }
    }

    /**
     * 场地的点击事件
     */
    private class ClickItem implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            List<Object> seatPosList = (List<Object>) v.getTag();
            int fieldPos = (int) seatPosList.get(0);//场地号的位置
            int timePos = (int) seatPosList.get(1);//场地号的时间

            HVVenueItemBean mHVVenueItemBean = mSeatOrderManger.getHVVenueItemBean(fieldPos, timePos, mpHVVenueItemBean);//点击的场地详情bean
            //场次ID
            String mVenueItemId=mHVVenueItemBean.getVenueItemId();
            Logger.e(" mHVVenueItemBean.getItemState()=" + mHVVenueItemBean.getItemState());
            if(Constants.SEAT_SOLD_STATE == mHVVenueItemBean.getIsSelected()){
                return;
            }
            if (Constants.SEAT_SELECTED == mHVVenueItemBean.getIsSelected()) {//已选择状态 就设置取消
                v.setBackgroundResource(R.drawable.sp_seat_nom);
                mMpSelectBeans.remove(mVenueItemId);
                doUpDateSeatSelcted(CANCEL, mHVVenueItemBean);
                editHVVenueItemBean(fieldPos, timePos, Constants.SEAT_CAN_SELECT);//更改状态
                ((TextView)v).setTextColor(getResources().getColor(R.color.c_333333));

            } else if (Constants.SEAT_CAN_SELECT == mHVVenueItemBean.getIsSelected()) {//未选择状态  就设置选择
                if (mOrderHVVenueItemBean.size() >= mMaxCount) {//判断是否已经超出最大的范围
                    ToastUtil.showToast(mContext, "最多只能选"+mMaxCount+"个");
                    return;
                }
                mMpSelectBeans.put(mVenueItemId,v);
                v.setBackgroundResource(R.drawable.sp_seat_selcted);
                ((TextView)v).setTextColor(getResources().getColor(R.color.white));
                doUpDateSeatSelcted(ADD, mHVVenueItemBean);
                editHVVenueItemBean(fieldPos, timePos, Constants.SEAT_SELECTED);
            }
            Logger.e("mview.size=" + mMpSelectBeans.size());
            checkIsOrderSeat();

        }
    }

    /**
     * 更新数据源
     *
     * @param type             是添加位置还是取消
     * @param mHVVenueItemBean 被选中的bean
     *                         更新价格 更新列表
     */

    private void doUpDateSeatSelcted(int type, HVVenueItemBean mHVVenueItemBean) {
        if (type == ADD) {
            mOrderHVVenueItemBean.add(mHVVenueItemBean);
            mSeatOrderAdapter.setHVVenueItemBeanList(mOrderHVVenueItemBean);
            mSeatOrderAdapter.notifyDataSetChanged();
            double currPri = mHVVenueItemBean.getPrice();
            countPrice(currPri);


        } else if (type == CANCEL) {
            mOrderHVVenueItemBean.remove(mHVVenueItemBean);
            for(int pos=0;pos<mOrderHVVenueItemBean.size();pos++){//根据对象的id移除对应的对象
                HVVenueItemBean mTempBean=mOrderHVVenueItemBean.get(pos);
                if(mTempBean.getVenueItemId().equals(mHVVenueItemBean.getVenueItemId())){
                    mOrderHVVenueItemBean.remove(pos);
                    break;
                }
            }
            mSeatOrderAdapter.setHVVenueItemBeanList(mOrderHVVenueItemBean);
            mSeatOrderAdapter.notifyDataSetChanged();
            double currPri = -mHVVenueItemBean.getPrice();
            countPrice(currPri);
        }
        checkIsShowBottom();
    }

    /**
     * 根据ID取消 场次
     * @param mGymId 场次Id
     */
    private void doUpDateSeatSelcted(String mGymId) {
//            mOrderHVVenueItemBean.remove(mHVVenueItemBean);
            double mPrice=0;
            for(int pos=0;pos<mOrderHVVenueItemBean.size();pos++){//根据对象的id移除对应的对象
                HVVenueItemBean mTempBean=mOrderHVVenueItemBean.get(pos);
                if(mTempBean.getVenueItemId().equals(mGymId)){

                    mPrice=mTempBean.getPrice();
                    mOrderHVVenueItemBean.remove(pos);
                    break;
                }
            }
            mSeatOrderAdapter.setHVVenueItemBeanList(mOrderHVVenueItemBean);
            mSeatOrderAdapter.notifyDataSetChanged();
            double currPri = -mPrice;
            countPrice(currPri);
        checkIsShowBottom();
    }




    /**
     * 设置总价格
     *
     * @param currPri 当前价格 选择为正取消为负
     */

    private void countPrice(double currPri) {
        mAllPrice = mAllPrice + currPri;
       /* mTvSeatPrice.setText(DecimalUtils.doubleToIntOrD(mAllPrice));*/
//        setTextView(DecimalUtils.doubleToIntOrD(mAllPrice),mTvSeatPrice);
        mTvSeatPrice.setText(DecimalUtils.setPriceStyle(mContext,mAllPrice,R.dimen.price_text_size_21,R.dimen.price_text_size_18,true));
    }
    /*private void setTextView(String prise,TextView mTv) {
        prise += "元";
        int end = prise.length();
        Spannable textSpan = new SpannableStringBuilder(prise);
        textSpan.setSpan(new AbsoluteSizeSpan(60), 0, end - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        textSpan.setSpan(new AbsoluteSizeSpan(40), end - 1, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        mTv.setText(textSpan);
    }*/

    /**
     * 获得时间差
     *
     * @param mHVVenueItemBean item详情信息
     * @return 秒
     */

    private float getTimeDis(HVVenueItemBean mHVVenueItemBean) {
        float mTimeDis = 0;
        long mStartTimeS=mHVVenueItemBean.getItemStartTime();
        long mEndTimeS=mHVVenueItemBean.getItemEndTime();
        long mStartTime = mStartTimeS * 1000;
        long mEndTime = mEndTimeS * 1000;
//        mTimeDis = DateUtil.timeToDate(mEndTime).getHours() - DateUtil.timeToDate(mStartTime).getHours(); //不支持半个小时
        mTimeDis = ((mEndTime - mStartTime)/(float)3600000);//支持半个小时
        return mTimeDis;
    }

    /**
     * @param mHVVenueItemBeanCur 当前的ItemBean
     * @param mHVVenueItemBeanPre 上一个的ItemBean
     * @return 当前的开始时间与上一个的结束时间的差
     */

    public float getItemSToStTime(HVVenueItemBean mHVVenueItemBeanCur, HVVenueItemBean mHVVenueItemBeanPre) {
        float mItemTimeDIs = 0;
       /* int mCItemStartTime = DateUtil.intToHourGetInt(mHVVenueItemBeanCur.getItemStartTime());//获取Item开始时间
        int mPItemendTiem = DateUtil.intToHourGetInt(mHVVenueItemBeanPre.getItemEndTime());*/
//        mItemTimeDIs = mCItemStartTime - mPItemendTiem;
        //支持半个小时
        int intCurStartT=mHVVenueItemBeanCur.getItemStartTime();//当前的Item的开始时间秒
        int intendT=mHVVenueItemBeanPre.getItemEndTime();//上一个Item的结束时间秒
        mItemTimeDIs=(intCurStartT-intendT)/(float)3600;//时间差
        return mItemTimeDIs;
    }

    /**
     * 展示场地的场号的item
     */

    private void doShowVeNum() {
        venueFieldList = mHVVenueItemInfoBean.getVenueFieldList();

        for (HVVenueFieldBean mHVVenueFieldBean : venueFieldList) {
            TextView tvGymNum = new TextView(this);
            tvGymNum.setLayoutParams(new ViewGroup.LayoutParams(SizeUtils.dp2px(this, 50), SizeUtils.dp2px(this, ViewGroup.LayoutParams.WRAP_CONTENT)));
            //设置场地名称的字体大小跟颜色
            tvGymNum.setTextColor(getResources().getColor(R.color.c_666666));
            tvGymNum.setTextSize(TypedValue.COMPLEX_UNIT_DIP,ELEVEN_DP);
            tvGymNum.setText(mHVVenueFieldBean.getVenueFieldName());
            mLlGymNumber.addView(tvGymNum);
            mLlGymNumber.setGravity(Gravity.CENTER);
            tvGymNum.setGravity(Gravity.CENTER);
        }

    }

    /**
     * 展示时间的item
     */

    private void doShowTimeItem() {
        ArrayList<Integer> mStartTAndEndT=mSeatOrderManger.getStartTimeAndEndTime(mHVVenueItemInfoBean.getVenueItemList());
        startTime=mStartTAndEndT.get(0);
        endTime=mStartTAndEndT.get(1);
        for (int st = startTime; st <= endTime; st++) {
            TextView tvTime = new TextView(this);
            int tempSt = st;
            tvTime.setLayoutParams(new ViewGroup.LayoutParams(SizeUtils.dp2px(this, 50), SizeUtils.dp2px(this, SINGLEHEIGH)));
            if(tempSt>=24){//次日
                tvTime.setText("次日"+(tempSt - 24)+ ":00");
            }else{
                tvTime.setText(tempSt+ ":00");
            }
            tvTime.setTextColor(mContext.getResources().getColor(R.color.c_666666));
            tvTime.setTextSize(TypedValue.COMPLEX_UNIT_DIP,TEN_DP);
            tvTime.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
            mLlTime.addView(tvTime);
        }

    }

    /**
     * 获取场馆周时间
     */

    private void getVenueWeekTimesList() {
        loadingView.show();
        IVenueService.getVenueWeekTimesList(this, venueId, projectId, false, new ObjectCallback<HVVenueWeekTimesInfoBean>() {
            @Override
            public void onSuccess(HVVenueWeekTimesInfoBean response, String message) {
                dialogDis();
                if (null != response) {
                    mProjectName=response.getProjectName();//项目名称
                     mVenueItemSpecific=response.getVenueItemSpecific();//特殊说明
                    mIvBuyInfo.setVisibility(StringUtils.isNull(mVenueItemSpecific)?View.GONE:View.VISIBLE);//如果是空的就隐藏
                    setTitle(mProjectName);
                     mMaxCount=response.getMaxReserve();//最大能预定的数量
                    //周场次数组
                     ArrayList<HVVenueWeekTimesBean> venueWeekTimes=response.getVenueWeekTimes();
                    mHVVenueWeekTimesBeanList.addAll(venueWeekTimes);
                    getDateAndWeekList();
                    mSeatTabAdapter.setHVVenueWeekTimesBeanList(mHVVenueWeekTimesBeanList);
                    mSeatTabAdapter.notifyDataSetChanged();
                    /*initSeatTab();*/
                   /* initOrderViewpager();*/
                    if(mCurTime!=0){//当前时间不为0 说明是以时间的参数传入 mWeekPos没传 于是根据没CurTime计算出mWeekPos
                        for(int i=0;i<mHVVenueWeekTimesBeanList.size();i++){
                            int time=mHVVenueWeekTimesBeanList.get(i).getVenueTime();
                            if(mCurTime==time){
                                mWeekPos=i;
                                break;
                            }
                        }
                    }
                    mShortAdress=response.getShortAddress();
                    mGymName =response.getVenueName();
                    mSeatTabAdapter.setSelection(mWeekPos);
                    mSeatTabAdapter.notifyDataSetChanged();
                    //获取场次的信息
                    int time = mHVVenueWeekTimesBeanList.get(mWeekPos).getVenueTime();
                    getVenueItemList(time);
                }
            }

            @Override
            public void onErrorT(int code, HVVenueWeekTimesInfoBean response, String errorMessage) {
                dialogDis();
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
            }
        });
    }

    /**
     * 获取日期和星期并拼接列表
     */
    private void getDateAndWeekList() {

        for (HVVenueWeekTimesBean mHVVenueWeekTimesBean : mHVVenueWeekTimesBeanList
                ) {
            long dt = mHVVenueWeekTimesBean.getVenueTime();//转化为毫秒的时间戳
            long dateTime = dt * 1000;
            String mDateS = DateUtil.stampToDate(dateTime);
            String mWeek = DateUtil.getWeek(dateTime);
            String mDateAndWeek = new StringBuilder(mWeek).append("\n").append(mDateS).toString();
            Logger.e("mDateAndWeek=" + mDateAndWeek);
            mDateAndWeekList.add(mDateAndWeek);
        }
    }

    /**
     * 初始化TabLayout
     */

    private void initSeatTab() {
        //tablayout 赋值
      /*  for (int i = 0; i < mDateAndWeekList.size(); i++) {//给tablayout赋值
            mSeatTab.addTab(mSeatTab.newTab().setText(mDateAndWeekList.get(i)));
        }*/
        mSeatTabAdapter = new SeatTabAdapter(mContext);
        mHvSeatTab.setAdapter(mSeatTabAdapter);
    }

    @Override
    public void onScrollChanged(MyHroScrollView scrollView, int x, int y, int oldx, int oldy) {
        mHv1.scrollTo(x, mHv1.getTop());
    }

    /**
     * 检查预定座位的订单是否需要显示
     */
    private void checkIsOrderSeat() {
        if (null == mOrderHVVenueItemBean || mOrderHVVenueItemBean.size() == 0) {
            mLlSeatOrderLayout.setVisibility(View.GONE);
        } else {
            mLlSeatOrderLayout.setVisibility(View.VISIBLE);

        }

    }

    /**
     * 更改mHVVenueItemBean的属性放回mp中
     *
     * @param state 改变的状态
     */
    public void editHVVenueItemBean(int fieldPos, int timePos, int state) {
        List<HVVenueItemBean> mHVVenueItemBeanList = mpHVVenueItemBean.get(fieldPos);
        HVVenueItemBean mHVVenueItemBean = mHVVenueItemBeanList.get(timePos);
        mHVVenueItemBean.setIsSelected(state);
    }

    /**
     * 取消场馆的接收事件
     *
     * @param mUiEvent
     */

    @Subscribe
    public void cacelSeat(UiEvent mUiEvent) {
        if (EventConstant.S_CANCEL_SEAT.equals(mUiEvent.getKey())) {//取消选择
            int pos = (int) mUiEvent.getObject();
            HVVenueItemBean mHVVenueItemBean = mOrderHVVenueItemBean.get(pos);
            for (int i = 0; i < mpHVVenueItemBean.size(); i++) {//遍历所有的bean更改状态为未选择
                List<HVVenueItemBean> mHVVenueItemBeanList = mpHVVenueItemBean.get(i);
                for (HVVenueItemBean mHVVenueItemBean1 : mHVVenueItemBeanList) {
                    if (mHVVenueItemBean.getVenueFieldId().equals(mHVVenueItemBean1.getVenueFieldId()) && mHVVenueItemBean.getItemStartTime() == mHVVenueItemBean1.getItemStartTime()) {
                        mHVVenueItemBean1.setIsSelected(Constants.SEAT_CAN_SELECT);
                    }
                }
            }
            doUpDateSeatSelcted(CANCEL, mHVVenueItemBean);
            //根据mVenueItemId 来更新View的状态
            String mVenueItemId=mHVVenueItemBean.getVenueItemId();

            mMpSelectBeans.get(mVenueItemId).setBackgroundResource(R.drawable.sp_seat_nom);
            ((TextView) mMpSelectBeans.get(mVenueItemId)).setTextColor(getResources().getColor(R.color.c_333333));
            mMpSelectBeans.remove(mVenueItemId);
        }else if(EventConstant.FLAG_GYM_PAY_SUC.equals(mUiEvent.getKey())){//从预定场馆进入 支付成功finish
            finish();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //activity销毁的时候注销EventBus
        EventBus.getDefault().unregister(this);
        UMShareAPI.get(this).release();
    }

    /**
     * 没有选中的就隐藏
     */
    public void checkIsShowBottom(){
        if(mOrderHVVenueItemBean.size()==0){
            mLlSeatOrderLayout.setVisibility(View.GONE);
        }else
            mLlSeatOrderLayout.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 场次提醒的对话框
     * @param mGymIDs 场馆Id
     */

    public void doShowCancelDialog(final ArrayList<String> mGymIDs){
        final ComDialog mSeatRemindDialog=CommonDialogUtils.dialog(SeatChoseActivity.this,getSupportFragmentManager(),getString(R.string.str_seat_remind),getString(R.string.str_seat_ordered));
        mSeatRemindDialog.setCancelGone();
        mSeatRemindDialog.setSubmit(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSeatRemindDialog.dismiss();

                doCancelSeat(mGymIDs);
            }
        });
    }

    /**
     * 将已预订的场次取消
     * @param mGymIDs
     */

    private void doCancelSeat(ArrayList<String> mGymIDs) {
        if(StringUtils.isNull(mGymIDs)){
            return;
        }
        for (String mGymId :mGymIDs ){
            doUpDateSeatSelcted( mGymId);
            for (int i = 0; i < mpHVVenueItemBean.size(); i++) {//遍历所有的bean更改状态为未选择
                List<HVVenueItemBean> mHVVenueItemBeanList = mpHVVenueItemBean.get(i);
                for (HVVenueItemBean mHVVenueItemBean1 : mHVVenueItemBeanList) {
                    if (mGymId.equals(mHVVenueItemBean1.getVenueItemId()) ) {
                        mHVVenueItemBean1.setIsSelected(Constants.SEAT_SOLD_STATE);
                    }
                }
            }
            //根据mVenueItemId 来更新View的状态
            mMpSelectBeans.get(mGymId).setBackgroundResource(R.drawable.sp_seat_sold);
            ((TextView) mMpSelectBeans.get(mGymId)).setText("");
            mMpSelectBeans.remove(mGymId);
        }
    }
}